package com.hexacta.hrs.security.ldap;

import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.ldap.ContextSource;
import org.springframework.ldap.support.LdapContextSource;

/**
 * {@link FactoryBean} de {@link ContextSource}.
 * 
 * @author pgarcia
 */
public class LdapContextSourceFactoryBean implements LdapConfigurable, FactoryBean, InitializingBean {

    /** la base a configurar. */
    private String base;

    /** el userName a configurar. */
    private String userName;

    /** la url a configurar. */
    private String url;

    /** ldapConfiguratorBean para hacer dd al configurar. */
    private LdapConfiguratorBean ldapConfiguratorBean;

    /** el password a configurar. */
    private String password;

    /** Constructor default. */
    public LdapContextSourceFactoryBean() {
        super();
    }

    /** @see LdapConfigurable#setBase(String) */
    public void setBase(final String base) {
        this.base = base;
    }

    /** @see LdapConfigurable#setPassword(String) */
    public void setPassword(final String password) {
        this.password = password;
    }

    /** @see LdapConfigurable#setUrl(String) */
    public void setUrl(final String url) {
        this.url = url;
    }

    /**
     * Setter.
     * 
     * @param ldapConfiguratorBean
     *            el/la ldapConfiguratorBean
     */
    public final void setLdapConfiguratorBean(final LdapConfiguratorBean ldapConfiguratorBean) {
        this.ldapConfiguratorBean = ldapConfiguratorBean;
    }

    /** @see LdapConfigurable#setUserName(String) */
    public void setUserName(final String userName) {
        this.userName = userName;
    }

    /** @see FactoryBean#getObject() */
    public Object getObject() throws Exception {
        if (this.ldapConfiguratorBean == null) {
            return null;
        }

        this.ldapConfiguratorBean.configure(this);

        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(this.url);
        contextSource.setBase(this.base);
        contextSource.setUserName(this.userName);
        contextSource.setPassword(this.password);

        contextSource.afterPropertiesSet();
        return contextSource;
    }

    /** @see FactoryBean#getObjectType() */
    public Class getObjectType() {
        return LdapContextSource.class;
    }

    /** @see FactoryBean#isSingleton() */
    public boolean isSingleton() {
        return true;
    }

    /** @throws Exception */
    public void afterPropertiesSet() throws Exception {
        Validate.notNull(this.ldapConfiguratorBean);
    }
}
